package com.hm.hall.commons.util; /**
 * cn.itcast.bbs.util.CookieUtil
 * 2014-5-26
 * Cookie操作工具类
 * gyy
 */


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {

    // ***
    public static final String WX_LOGIN_STUBINFO = "loginStubInfo"; // 微信登录 鉴权操作参数对象
    private static final int COOKIE_MAX_AGE = 7 * 24 * 3600;

    public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name) {
        if (null == name) {
            return;
        }
        Cookie cookie = getCookie(request, name);
        if (null != cookie) {
            cookie.setPath("/");
            cookie.setValue("");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
    }

    /**
     * 根据Cookie名称得到Cookie对象，不存在该对象则返回Null
     */
    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (null == cookies || null == name || name.length() == 0) {
            return null;
        }
        Cookie cookie = null;
        for (Cookie c : cookies) {
            if (name.equals(c.getName())) {
                cookie = c;
                break;
            }
        }
        return cookie;
    }


    /**
     * 根据名字获取 cookie 的值,再转的对象
     */
    public static <T> T getCookieValueObj(HttpServletRequest request, String name, Class<T> clazz) {
        Cookie cookie = getCookie(request, name);
        if (cookie == null) {
            return null;
        }
        return JsonUtils.parseObject(cookie.getValue(), clazz);
    }


    /**
     * 添加一条新的Cookie，默认7天过期时间(单位：秒)
     */
    public static void addCookie(HttpServletResponse response, String name, String value) {
        addCookie(response, name, value, COOKIE_MAX_AGE);
    }

    /**
     * 添加一条新的Cookie，可以指定过期时间(单位：秒)
     */
    public static void addCookie(HttpServletResponse response, String name, String value, int maxSec) {
        if (null == name) {
            return;
        }
        if (null == value) {
            value = "";
        }
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        if (maxSec != 0) {
            cookie.setMaxAge(maxSec);
        } else {
            cookie.setMaxAge(COOKIE_MAX_AGE);
        }
        response.addCookie(cookie);
    }
}